package aplicativo.conversor;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import aplicativo.conversor.R;

import aplicativo.conversor.util.Calculos;

public class TemperaturaActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.temperatura);
		preencherSpinner(new String[]{	"Celsius para Fahrenheit",
										"Fahrenheit para Celsius"});
		converterClick();
	}

    private void converterClick() {
    	final EditText text = (EditText) findViewById(R.temperatura.tempConverter);
    	final Spinner sp = (Spinner)findViewById(R.temperatura.spTemperaturas);
    	
    	
    	Button bt = (Button) findViewById(R.temperatura.btConverter);
    	bt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final String tempCalculada = calculartemperatura(sp, text);
				showMessage("Temperatura convertida", 
							tempCalculada,
							"OK",
							R.drawable.icon);
			}
		});
    }
	
	private String calculartemperatura(Spinner spinner, EditText text) {
		double temperatura = new Double(text.getText().toString());
		String opcao = spinner.getSelectedItem().toString();
		
		if ("Celsius para Fahrenheit".equalsIgnoreCase(opcao)) {
			temperatura = Calculos.celsiusToFahrenheit(temperatura);
		} else if ("Fahrenheit para Celsius".equalsIgnoreCase(opcao)) {
			temperatura = Calculos.fahrenheitToCelsius(temperatura);
		}
		return temperatura + "";
	}

	public void showMessage(String titulo, String mensagem, String botao, int icone) {
		AlertDialog.Builder janela = new AlertDialog.Builder(this);
		janela.setTitle(titulo);
		janela.setMessage(mensagem);
		final AlertDialog dialog = janela.create();
		if (icone != 0) {
			janela.setIcon(icone);
		}
		dialog.setButton(botao, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				dialog.dismiss();
			}
		});
		dialog.show();
	
	}

	private void preencherSpinner(String[] valores) {
		Spinner sp = (Spinner)findViewById(R.temperatura.spTemperaturas);
    	ArrayAdapter<String> itens = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, valores);
    	sp.setAdapter(itens);
	}
	
}
